package com.bus.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.bus.admin.bean.AppMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 张子艺
 * @packge com.xbxkj.config.config
 * @data 2019-06-11 12:00
 * @project Metaphysics
 */
@ServerEndpoint(value = "/websocket/{userId}/{type}" )
@Component
public class MyWebSocket {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<String,MyWebSocket> webSocketSet = new ConcurrentHashMap<String,MyWebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String  thisType;



    //此处是解决无法注入的关键
    private static ApplicationContext applicationContext;
    //要注入的service或者dao
    public static void setApplicationContext(ApplicationContext applicationContext) {
        MyWebSocket.applicationContext = applicationContext;
    }

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value = "userId") String param, @PathParam(value = "type") String type, Session session) {
        this.session = session;
        webSocketSet.put(param,this);     //加入set中
        thisType=type;
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("来自客户端的消息:" + message);
        AppMsg appMsg=  JSONObject.parseObject(message, AppMsg.class);

        sendInfo(message);

    }

    /**
     * 发生错误时调用
     *@OnError
     **/
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        try {
            this.session.getBasicRemote().sendText(message);
        }catch (Exception e){
            webSocketSet.remove(this);  //从set中删除
        }

        //this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (String key : webSocketSet.keySet()) {
            try {
                String type=webSocketSet.get(key).thisType;
                //如果 循环到后台 那么发送提醒
                if(type.equals("admin")){
                    webSocketSet.get(key).sendMessage(message);
                }

            } catch (IOException e) {
                continue;
            }
        }
    }

    /**
     * 单发自定义消息
     * userId 给谁发
     * */
    public static void sendToUser(String message,String userId) throws IOException {
        for (String key : webSocketSet.keySet()) {
            if(key.equals(userId)){
                try {
                    webSocketSet.get(key).sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}
